package cn.time1024.time_app.ui.dashboard

import android.graphics.Paint
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.core.content.ContextCompat
import com.example.timeassistant.network.ApiService
import cn.time1024.time_app.R
import com.google.android.material.chip.Chip

class TasksAdapter(
    private val items: MutableList<ApiService.TaskItem> = mutableListOf(),
    private val onToggleComplete: (ApiService.TaskItem, Boolean) -> Unit,
    private val onEdit: (ApiService.TaskItem) -> Unit,
    private val onDelete: (ApiService.TaskItem) -> Unit,
    private val onTogglePinned: (ApiService.TaskItem) -> Unit
) : RecyclerView.Adapter<TasksAdapter.VH>() {

    class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val cbCompleted: CheckBox = itemView.findViewById(R.id.cbCompleted)
        val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
        val tvDesc: TextView = itemView.findViewById(R.id.tvDesc)
        val tvDue: TextView = itemView.findViewById(R.id.tvDue)
        val chipPriority: Chip = itemView.findViewById(R.id.chipPriority)
        val chipStatus: Chip = itemView.findViewById(R.id.chipStatus)
        val tvPinned: TextView = itemView.findViewById(R.id.tvPinned)
        val btnEdit: Button = itemView.findViewById(R.id.btnEdit)
        val btnDelete: Button = itemView.findViewById(R.id.btnDelete)
        val btnPin: Button = itemView.findViewById(R.id.btnPin)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false)
        return VH(view)
    }

    override fun getItemCount(): Int = items.size

    /** 绑定任务项视图并根据状态、优先级、截止日期更新UI */
    override fun onBindViewHolder(holder: VH, position: Int) {
        val item = items[position]
        holder.tvTitle.text = item.title ?: "(未命名)"
        holder.tvDesc.text = item.description ?: ""
        holder.tvDue.text = "截止日期: ${item.dueDate ?: "-"}"

        // 优先级中文与颜色映射（仅给值着色，标签颜色保持默认）
        val ctx = holder.itemView.context
        val defaultColor = Color.parseColor("#888888")
        val red = ContextCompat.getColor(ctx, android.R.color.holo_red_dark)
        val yellow = ContextCompat.getColor(ctx, android.R.color.holo_orange_dark)
        val green = ContextCompat.getColor(ctx, android.R.color.holo_green_dark)

        val priorityCode = item.priority ?: ""
        val priorityLabel = when (priorityCode) {
            "high" -> "高"
            "medium" -> "中"
            "low" -> "低"
            else -> "-"
        }
        holder.chipPriority.text = priorityLabel
        val pColor = colorForPriorityLabel(priorityLabel, ctx, red, yellow, green, defaultColor)
        holder.chipPriority.chipBackgroundColor = android.content.res.ColorStateList.valueOf(pColor)
        holder.chipPriority.setTextColor(Color.WHITE)

        // 状态颜色映射：未完成=黄色，已完成=绿色（仅给值着色，标签颜色保持默认）
        val statusText = item.status ?: "-"
        holder.chipStatus.text = statusText
        val sColor = colorForStatusText(statusText, ctx, yellow, green, defaultColor)
        holder.chipStatus.chipBackgroundColor = android.content.res.ColorStateList.valueOf(sColor)
        holder.chipStatus.setTextColor(Color.WHITE)

        // 截止日期过期高亮（未完成时红色提示）
        val dueMillis = parseDueMillis(item.dueDate)
        if (dueMillis != null && System.currentTimeMillis() > dueMillis && item.status != "已完成") {
            holder.tvDue.setTextColor(red)
        } else {
            holder.tvDue.setTextColor(Color.parseColor("#6b7280"))
        }

        // 置顶状态与按钮文案
        holder.tvPinned.visibility = if (item.pinned == "Y") View.VISIBLE else View.GONE
        holder.btnPin.text = if (item.pinned == "Y") "取消置顶" else "置顶"
        val completed = item.status == "已完成"
        // 先清除旧监听，避免 RecyclerView 复用导致程序设置触发回调
        holder.cbCompleted.setOnCheckedChangeListener(null)
        holder.cbCompleted.isChecked = completed
        holder.tvTitle.paintFlags = if (completed) {
            holder.tvTitle.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        } else {
            holder.tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
        }

        // 仅响应用户交互触发，避免数据绑定过程误触发更新接口
        holder.cbCompleted.setOnCheckedChangeListener { buttonView, isChecked ->
            if (!buttonView.isPressed) return@setOnCheckedChangeListener
            onToggleComplete(item, isChecked)
        }
        holder.btnEdit.setOnClickListener { onEdit(item) }
        holder.btnDelete.setOnClickListener { onDelete(item) }
        holder.btnPin.setOnClickListener { onTogglePinned(item) }
    }

    /** 替换列表数据并刷新 */
    fun replaceAll(newItems: List<ApiService.TaskItem>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }

    /** 追加列表数据并增量刷新 */
    fun appendAll(newItems: List<ApiService.TaskItem>) {
        val start = items.size
        items.addAll(newItems)
        notifyItemRangeInserted(start, newItems.size)
    }

    /** 根据优先级中文映射背景色 */
    private fun colorForPriorityLabel(label: String, ctx: android.content.Context, red: Int, yellow: Int, green: Int, def: Int): Int {
        return when (label) { "高" -> red; "中" -> yellow; "低" -> green; else -> def }
    }

    /** 根据状态中文映射背景色 */
    private fun colorForStatusText(text: String, ctx: android.content.Context, yellow: Int, green: Int, def: Int): Int {
        return when (text) { "未完成" -> yellow; "已完成" -> green; else -> def }
    }

    /** 解析截止日期字符串为毫秒时间戳，兼容常见格式 */
    private fun parseDueMillis(due: String?): Long? {
        if (due.isNullOrBlank()) return null
        val patterns = arrayOf("yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd")
        for (p in patterns) {
            try {
                val sdf = java.text.SimpleDateFormat(p, java.util.Locale.getDefault())
                return sdf.parse(due)?.time
            } catch (_: Exception) {}
        }
        return null
    }
}
